from django.shortcuts import render, redirect, HttpResponse
from django import forms
from app01 import models
from app01.utils.Bootstrap import BootStrapForm
from app01.utils.encrypt import md5
from app01.utils.code import check_code


# required=True必填不能为空,默认True
# render_value=True,错误以后不会清空数据
class LoginForm(BootStrapForm):
    username = forms.CharField(label="用户名",
                               widget=forms.TextInput,
                               required=True)
    password = forms.CharField(label="密码",
                               widget=forms.PasswordInput(render_value=True),
                               required=True)
    code = forms.CharField(label="验证码",
                           widget=forms.TextInput,
                           required=True)

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


# class LoginModelForm(forms.ModelForm):
#     class Meta:
#         model = models.Admin
#         fields = ['username', 'password']
def login(request):
    """登录"""
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功后获取到的用户名和密码和验证码
        # print(form.cleaned_data)
        user_input__code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")
        # upper()大写
        if code.upper() != user_input__code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})
        # 去数据库校验他的密码和用户名
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # 用户名和密码正确
        # 网站生成随机字符串:写到用户浏览器的cookie中，再写入到session中
        request.session["info"] = {'id': admin_object.id, 'username': admin_object.username}
        # 7天后登录过期，session保存7天
        request.session.set_expiry(60*60*24*7)
        return redirect("/admin/list/")
    return render(request, 'login.html', {'form': form})


def logout(request):
    """注销"""
    # 清除当前用户的session
    request.session.clear()
    return redirect('/login/')


from io import BytesIO


def image_code(request):
    """生成图片验证码"""
    img, code_string = check_code()
    # 写入到自己的session中(以便后续获取验证码再进行校验)
    request.session['image_code'] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
